package net.airtheva.uniqueTask5;

import java.util.ArrayList;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.widget.RemoteViews;

public class WeatherWidget extends AppWidgetProvider {

	public static final String TAG = "WeatherWidget";
	
	public static final int REQUEST_CODE_APP_WIDGET_REQUEST = 0;
	
	public static final String KEY_APP_WIDGET_ID = "appWidgetID";
	
	public static final String KEY_WEATHER_ICON_URI = "weatherIconURI";
	public static final String KEY_LOCATION_NAME = "locationName";
	public static final String KEY_WEATHER = "weather";
	public static final String KEY_TEMPERATURE = "temperature";
	
	static final ArrayList<Integer>AppWidgetIDs;
	
	static {
		AppWidgetIDs = new ArrayList<Integer>();
	}
	
	@Override
	public void onReceive(Context context, Intent intent) {
		
		if(intent.getAction().equals(WeatherService.BROADCAST_ACTION_APPWIDGET_UPDATE)) {
			updateWidget(context, intent);
		}
		else {
			super.onReceive(context, intent);
		}
		
	}

	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
		
		for(int i = 0; i < appWidgetIds.length; i++) {
			
			int appWidgetID = appWidgetIds[i];
			
			if(!AppWidgetIDs.contains(appWidgetID)) {
				AppWidgetIDs.add(appWidgetID);
			}
			
			Intent intent = new Intent();
			intent.setAction(WeatherService.BROADCAST_ACTION_APPWIDGET_REQUEST);
			intent.putExtra(KEY_APP_WIDGET_ID, appWidgetID);
			context.sendBroadcast(intent);
			
		}
		
	}

	void updateWidget(Context context, Intent intent) {
		
		AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
		
		int appWidgetID = intent.getIntExtra(KEY_APP_WIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
		
		String weatherIconURI = intent.getStringExtra(KEY_WEATHER_ICON_URI);
		String locationName = intent.getStringExtra(KEY_LOCATION_NAME);
		String weather = intent.getStringExtra(KEY_WEATHER);
		String temperature = intent.getStringExtra(KEY_TEMPERATURE);
		
		RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_weather);
		
		remoteViews.setImageViewUri(R.id.widget_weather_weatherIcon, Uri.parse(weatherIconURI));
		remoteViews.setOnClickPendingIntent(R.id.widget_weather_weatherIcon, PendingIntent.getBroadcast(context, REQUEST_CODE_APP_WIDGET_REQUEST, intent, PendingIntent.FLAG_CANCEL_CURRENT));
		remoteViews.setTextViewText(R.id.widget_weather_locationName, locationName);
		remoteViews.setTextViewText(R.id.widget_weather_weather, weather);
		remoteViews.setTextViewText(R.id.widget_weather_temperature, temperature);
		intent.setAction(WeatherService.BROADCAST_ACTION_APPWIDGET_REQUEST);
		
		appWidgetManager.updateAppWidget(appWidgetID, remoteViews);
		
	}
	
}
